<template>
  <div class="app-main-container">
    <!-- <div class="app-main-title">开具历史</div> -->
    <div class="doumee-filter">
      <el-input v-model="filters.orderId" clearable placeholder="请输入订单编号" />
      <el-select
        v-model="filters.orderType"
        placeholder="请选择订单类型"
        clearable
      >
        <el-option
          v-for="item in orderTypeList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-input v-model="filters.userPhone" clearable placeholder="请输入用户手机号" />
      <el-select v-model="filters.type" placeholder="请选择抬头类型" clearable>
        <el-option
          v-for="item in typeList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-if="activeName == '0'" v-model="filters.status" placeholder="请选择审批类型" clearable>
        <el-option
          v-for="item in spList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input v-model="filters.companyTitle" clearable placeholder="请输入抬头名称" />
      <el-button v-preventReClick type="primary" @click="search">查找</el-button>
      <el-button v-preventReClick @click="clearList">清空</el-button>
    </div>
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="search"
      @clear="clearList"
    />
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-for="(em, dex) in tabList" :key="dex" :name="em.index" :label="em.name">
        <el-table
          v-if="activeName == '0'"
          ref="table"
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
        >
          <el-table-column
            align="center"
            label="用户信息"
            prop="userInfo"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="抬头类型"
            min-width="130"
            prop="type"
          >
            <template slot-scope="scope">
              {{
                scope.row.type == 0
                  ? "企业单位"
                  : scope.row.type == 1
                    ? "个人/非企业单位": ""
              }}
            </template></el-table-column>
          <el-table-column
            align="center"
            label="发票抬头"
            min-width="350"
            prop="companyTitle"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.companyTitle }} {{ scope.row.companyTax?'-' + scope.row.companyTax : "" }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="电子邮箱"
            prop="email"
            show-overflow-tooltip
            min-width="200"
          />
          <el-table-column
            align="center"
            label="订单编号"
            show-overflow-tooltip
            prop="orderIds"
            min-width="220"
          />
          <el-table-column
            align="center"
            label="可开票金额"
            prop="amot"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="审批人"
            show-overflow-tooltip
            prop="editor"
            min-width="120"
          />
          <el-table-column
            align="center"
            label="审批时间"
            prop="editTime"
            min-width="160"
          />
          <el-table-column
            align="center"
            label="备注"
            show-overflow-tooltip
            prop="editInfo"
            min-width="200"
          />
          <el-table-column
            align="center"
            label="状态"
            min-width="120"
            fixed="right"
            prop="editStatus"
          >
            <template slot-scope="scope">
              {{
                scope.row.editStatus == 1
                  ? "审批通过"
                  : scope.row.editStatus == 2
                    ? "审批拒绝": "待审批"
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <div v-if="meta.indexOf('MakeInvoiceApply') > -1 && scope.row.editStatus == 0" class="flex-cc">
                <el-button
                  v-preventReClick
                  type="text"
                  @click="spBtn(scope.row)"
                >审批</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="activeName == '0'" class="flex-cc doumee-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page.sync="pagination.page"
            hide-on-single-page
            @current-change="getListb"
          />
        </div>
        <el-table
          v-if="activeName == '1'"
          ref="tableb"
          v-loading="listLoading"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
        >
          <el-table-column
            align="center"
            label="用户信息"
            prop="userInfo"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column
            align="center"
            label="抬头类型"
            min-width="150"
            prop="type"
          >
            <template slot-scope="scope">
              <!-- 状态（0：未支付，1：超时未支付，3：支付成功） , -->
              {{
                scope.row.type == 0
                  ? "企业单位"
                  : scope.row.type == 1
                    ? "个人/非企业单位": ""
              }}
            </template></el-table-column>
          <el-table-column
            align="center"
            label="发票抬头"
            min-width="350"
            prop="companyTitle"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.companyTitle }} {{ scope.row.companyTax?'-' + scope.row.companyTax : "" }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="电子邮箱"
            prop="email"
            show-overflow-tooltip
            min-width="200"
          />
          <el-table-column
            align="center"
            label="订单编号"
            prop="orderIds"
            show-overflow-tooltip
            min-width="220"
          />
          <!-- <el-table-column
            align="center"
            label="订单类型"
            prop="orderType"
            min-width="200"
          >
            <template slot-scope="scope">
              <span>{{ orderTypeName(scope.row.orderType) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column
            align="center"
            label="订单金额"
            prop="amot"
            show-overflow-tooltip
            min-width="100"
          />
          <el-table-column
            align="center"
            label="开票人"
            prop="creator"
            show-overflow-tooltip
            min-width="120"
          />
          <el-table-column
            align="center"
            label="开票时间"
            prop="createTime"
            min-width="160"
          />
          <el-table-column
            align="center"
            label="是否红冲"
            prop="isRed"
            width="100"
          >
            <template slot-scope="scope">
              <!-- 状态（0：未支付，1：超时未支付，3：支付成功） , -->
              {{
                scope.row.isRed == 1
                  ? "已红冲"
                  :"未红冲"
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="130"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <div class="flex-cc">
                <el-button
                  v-if="scope.row.isRed == 0 || !scope.row.isRed"
                  v-preventReClick
                  type="text"
                  @click="hcBtn(scope.row)"
                >红冲</el-button>
                <el-button
                  v-if="scope.row.isRed == 1"
                  v-preventReClick
                  type="text"
                  @click="againBtn(scope.row)"
                >重发</el-button>
                <el-button
                  v-preventReClick
                  type="text"
                  @click="downloadBtn(scope.row.id)"
                >下载</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="activeName == '1'" class="flex-cc doumee-pagination">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :current-page.sync="pagination.page"
            hide-on-single-page
            @current-change="getList"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="审批" :visible.sync="visible" width="500px" :close-on-click-modal="modalDialog" :close-on-press-escape="modalDialog">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="6em" class="demo-ruleForm">
        <el-form-item label="审批状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见" prop="editInfo">
          <el-input
            v-model="ruleForm.editInfo"
            :autosize="{ minRows: 2, maxRows: 4}"
            maxlength="200"
            type="textarea"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submitForm('ruleForm')">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index'
import store from '@/store'
import { queryFormConfig } from './config'
import QueryForm from '@/components/QueryForm'
import { listInvoiceRecord, orderTypeList, listInvoiceApply, makeInvoiceApply, redFlush, redFlushAgain, getRedFlush } from '@/api'
export default {
  name: 'InvoiceList',
  components: {
    QueryForm
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      queryFormConfig,
      meta: [],
      subLoading: false,
      ruleForm: {},
      spList: [
        { label: '审批通过', value: '1' },
        { label: '审批拒绝', value: '2' }
      ],
      visible: false,
      list: [],
      pagination: {
        page: 1,
        rows: 10
      },
      total: 0,
      orderTypeList: [],
      typeList: [
        { value: '0', label: '企业单位' },
        { value: '1', label: '个人/非企业单位' }
      ],
      filters: {},
      listLoading: true,
      show: false,
      orderId: '',
      form: {},
      activeName: '0',
      tabList: [
        { index: '0', name: '开票申请' },
        { index: '1', name: '已开票' }
      ],
      rules: {
        price: [
          { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, required: true, message: '请输入正确课时总价(元),最多保留2位小数', trigger: 'blur' }
        ],
        info: [
          { required: true, message: '费用由线下退款，请具体描述退课原因', trigger: 'blue' }
        ],
        status: [
          { required: true, message: '请选择审批状态', trigger: 'change' }
        ],
        editInfo: [
          { required: true, message: '请输入审批意见', trigger: 'blue' }
        ]
      },
      applyId: ''
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getListb()
    this.getOrderTypeList()
  },
  activated() {
    if (this.$route.query.renovate) {
      this.search()
    }
  },
  methods: {
    spBtn(e) {
      this.applyId = e.id
      this.visible = true
      this.ruleForm = {}
      this.$refs['ruleForm'].resetFields()
    },
    downloadBtn(id) {
      getRedFlush({
        param: {
          id
        }
      })
        .then(res => {
          if (res.errorCode === '000000') {
            if (res.record.tsPdfUrl) {
              window.open(res.record.tsPdfUrl)
            }
          }
        })
    },
    hcBtn(row) {
      const that = this
      this.$confirm('此操作将红冲, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          redFlush({ param: { id: row.id, email: row.email }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success('红冲成功')
              that.getList(1)
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    againBtn(row) {
      const that = this
      this.$confirm('此操作将重新发送, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: () => {},
        beforeClose: (action, ctx, close) => {
          if (action !== 'confirm') {
            close()
            return
          }
          ctx.confirmButtonLoading = true
          redFlushAgain({ param: { id: row.id, email: row.email }}).then((res) => {
            ctx.confirmButtonLoading = false
            close()
            if (res.errorCode === '000000') {
              that.$message.success('发送成功')
              that.getList(1)
            }
          })
            .catch(() => { ctx.confirmButtonLoading = false })
        }
      }).finally(() => {})
    },
    submitForm(formName) {
      const that = this
      const param = this.ruleForm
      param.applyId = this.applyId
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.visible = false
          that.subLoading = true
          makeInvoiceApply({ param }).then(res => {
            that.subLoading = false
            if (res.errorCode === '000000') {
              that.$message.success('审批成功')
              that.getListb(1)
            }
          }).catch(() => {
            that.subLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClick(tab, event) {
      // console.log(this.activeName, 141)
      if (this.activeName === '0') {
        this.getListb(1)
      } else {
        this.getList(1)
      }
      // this.getSubjectBaiList()
    },
    // 获取订单类型列表
    getOrderTypeList() {
      orderTypeList({ param: { type: 'ORDER_TYPE_INVOICE_OPEN' }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.orderTypeList = res.recordList
        })
    },
    orderTypeName(b) {
      const arr = this.orderTypeList
      let c = ''
      arr.forEach(e => {
        if (e.id === b) {
          c = e.name
        }
      })
      return c
    },
    getListb(page) {
      this.listLoading = true
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      if (pagination.page === 1) {
        pagination.firstQueryTime = parseTime(new Date())
      }
      listInvoiceApply({ pagination, param: { venueId, ...filters }})
        .then(res => {
          this.listLoading = false
          if (res.errorCode === '000000') {
            this.list = res.recordList
            this.total = res.totalCount
            this.$refs.table.doLayout()
          }
        }).catch(() => {
          this.listLoading = false
        })
    },
    clearList() {
      this.filters = {}
      if (this.activeName === '0') {
        this.getListb(1)
      } else {
        this.getList(1)
      }
    },
    search() {
      if (this.activeName === '0') {
        this.getListb(1)
      } else {
        this.getList(1)
      }
    },
    getList(page) {
      this.listLoading = true
      const { filters, pagination } = this
      const venueId = sessionStorage.getItem('venueId')
      if (page) {
        pagination.page = page
        this.pagination.page = page
      }
      if (pagination.page === 1) {
        pagination.firstQueryTime = parseTime(new Date())
      }
      listInvoiceRecord({ pagination, param: { venueId, ...filters }})
        .then(res => {
          this.listLoading = false
          if (res.errorCode !== '000000') return
          this.list = res.recordList
          this.total = res.totalCount
          this.$refs.tableb.doLayout()
        }).catch(() => {
          this.listLoading = false
        })
    }
  }
}
</script>

